package com.ttxs.fileformathandling.utils;

import com.ttxs.fileformathandling.common.ErrorCode;
import com.ttxs.fileformathandling.exception.BusinessException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;


/**
 * 文件上传类
 *
 * @author cwt
 */
@Configuration
@Data
public class FileUtils {

    @Value("${upload.path}")
    public String path;


    /***
     * 按指定编码方式读取指定文件
     * @param filePath 文件路径
     * @param encoding 以什么编码方式读取文件
     * @return 将指定文件读出成字符串
     * @author cwt
     */

    public static String readFileToString(String filePath, String encoding) {
        //获取指定文件内容的总字节数
        byte[] encodedBytes;
        try {
            encodedBytes = Files.readAllBytes(Paths.get(filePath));
            return new String(encodedBytes, encoding);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件读取异常");
        }
    }

    public static void createFile(String inputPath) {
        File file = new File(inputPath);

        // 获取父目录
        File parentDir = file.getParentFile();

        // 检查目录是否存在，如果不存在则创建
        if (!parentDir.exists()) {
            if (!parentDir.mkdirs()) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "无法创建目录");
            }
        }
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建文件时出现错误");
        }
    }

    /**
     * 最多读取前5k数据
     *
     * @param filePath 文件地址
     * @return 返回读取的字符串
     */
    public static String readFileBytes(String filePath) {
        StringBuilder sb = new StringBuilder();

        try (FileInputStream inputStream = new FileInputStream(filePath)) {
            byte[] buffer = new byte[5120];
            int bytesRead = inputStream.read(buffer, 0, 5000);
            while (bytesRead != -1) {
                sb.append(new String(buffer, 0, bytesRead));
                bytesRead = inputStream.read(buffer, 0, 5000);
            }
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件读取异常");
        }

        return sb.toString();
    }


    public static String readFileLine(String filePath) {
        StringBuilder sb = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            int count = 0;
            while ((line = reader.readLine()) != null && count < 1) {
                sb.append(line).append(System.lineSeparator());
                count++;
            }
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件读取异常");
        }

        return sb.toString();
    }

    /***
     *将处理好的字符串写入到文件中
     * @param filePath 指定输出文件的路径
     * @param content 需要写入文件的内容
     * @param encoding 指定文件编码
     * @author cwt
     */

    public static void saveToFile(String filePath, String content, String encoding) {
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(Files.newOutputStream(Paths.get(filePath)), encoding))) {
            writer.write(content);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件写入异常");
        }
    }


    public boolean del(String filename) {
        File file = new File(path + File.separator + filename);
        return file.delete();
    }

    public boolean del(String path, String filename) {
        return new File(path + File.separator + filename).delete();
    }
}
